package com.jyou.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.jyou.business.User;
import com.jyou.dao.UserDAO;

public class UserDAOImpl implements UserDAO {
	private SessionFactory sessionFactory;
	public UserDAOImpl(){
		Configuration cfg = new Configuration().configure();
		sessionFactory = cfg.buildSessionFactory();
	}
	@Override
	public void save(User user) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			tx.begin();
			session.saveOrUpdate(user);
		}
		catch(Exception e){
			tx.rollback();
		}
		finally{
			session.close();
		}
	}

	@Override
	public void delete(User user) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			tx.begin();
			session.delete(user);
		}
		catch(Exception e){
			tx.rollback();
		}
		finally{
			session.close();
		}
	}

	@Override
	public void update(User user) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			tx.begin();
			session.update(user);
		}
		catch(Exception e){
			tx.rollback();
		}
		finally{
			session.close();
		}
	}

	@Override
	public User findById(int uid) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		try{
			return (User) session.get(User.class, uid);
		}
		finally{
			session.close();
		}
	}

	@Override
	public List<?> findAll() {
		// TODO Auto-generated method stub
		Session session = sessionFactory.openSession();
		try{
			Query query = session.createQuery("from User");
			return query.list();
		}
		finally{
			session.close();
		}
	}
}
